package cmd

import (
	"fmt"
	"os"
	"path"

	"gitee.com/xuender/oils/logs"
	"gitee.com/xuender/se"
	homedir "github.com/mitchellh/go-homedir"
	"github.com/spf13/cobra"
	"github.com/spf13/viper"
)

// nolint: gochecknoglobals
var (
	cfgFile string
	rootCmd = &cobra.Command{
		Use:     "se",
		Short:   "个人搜索引擎",
		Long:    `扫描本地目录或文件，生成倒排索引，方便文件内容搜索`,
		Version: "v1.1.0",
		Run: func(cmd *cobra.Command, args []string) {
			app := se.InitApp(se.NewContext(cmd))
			defer app.Close()

			app.Run()
		},
	}
)

// Execute 执行.
func Execute() {
	cobra.CheckErr(rootCmd.Execute())
}

// nolint: gochecknoinits
func init() {
	home := logs.PanicString(homedir.Dir())

	cobra.OnInitialize(initConfig)
	rootCmd.PersistentFlags().StringVar(&cfgFile, "config", "", "config file (default is $HOME/.se.toml)")
	rootCmd.PersistentFlags().String("db", path.Join(home, ".se"), "数据库目录")
	rootCmd.Flags().Int("width", 1000, "窗口宽度")
	rootCmd.Flags().Int("height", 800, "窗口高度")
	rootCmd.Flags().Uint("limit", 100, "显示条数")
}

// initConfig reads in config file and ENV variables if set.
func initConfig() {
	if cfgFile != "" {
		// Use config file from the flag.
		viper.SetConfigFile(cfgFile)
	} else {
		// Find home directory.
		home, err := homedir.Dir()
		cobra.CheckErr(err)
		// Search config in home directory with name ".se" (without extension).
		viper.AddConfigPath(home)
		viper.SetConfigName(".se")
	}

	viper.AutomaticEnv() // read in environment variables that match

	// If a config file is found, read it in.
	if err := viper.ReadInConfig(); err == nil {
		fmt.Fprintln(os.Stderr, "使用配置文件:", viper.ConfigFileUsed())
	}
}
